<?php
namespace app\common\model;

use think\Db;

class FormModel extends BaseModel
{
    protected $name = 'form'; //定义表单表
    //开启自动写入时间戳
    protected $autoWriteTimestamp = false;
    // 定义自动完成的属性
    protected $auto = []; //新增修改
    protected $insert = []; //插入
    protected $update = []; //修改

    /*读取器*/
    protected function getIsSystemTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-warning">普通</span>',
            1 => '<span class="label label-success">内置</span>',
        ];
        return $status[$data['is_system']];
    }

    protected function getFormStatusTextAttr($value, $data)
    {
        $status = [
            0 => '<span class="label label-warning">锁定</span>',
            1 => '<span class="label label-info">正常</span>',
        ];
        return $status[$data['form_status']];
    }
    /*修改器*/

    /**
     * 创建表单对应表
     * @param $tableName
     */
    public function createTable($tableName)
    {
        $sql = file_get_contents(APP_PATH . 'system/sql/form.sql');
        $sql = preg_replace(
            ['/@pre@/', '/@table@/'], [config('database.prefix'), 'form_' . $tableName],
            $sql
        );
        Db::execute($sql); //创建主表
    }

    /**
     * 删除表单
     * @param $formId
     */
    public function delData($formId)
    {
        $tableName = \think\Db::name('form')->where('form_id', $formId)->value('table_name');
        $tableName = config('database.prefix') . 'form_' . $tableName;
        Db::startTrans();
        try {
            //删除字段数据
            Db::table('form_field')->where('form_id', $formId)->delete();
            //删除对应表
            Db::execute('DROP TABLE IF EXISTS `' . $tableName . '`');
            //删除表单数据
            Db::table('form')->where('form_id', $formId)->delete();
            return true;
        } catch (Exception $e) {
            Db::rollback(); // 回滚事务
            $this->error = $e->getMessage();
            return false;
        }
    }

}




